package com.zcsy.manage.web.company;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.manage.model.base.Company;
import com.zcsy.manage.model.system.Dict;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.service.base.ICellInfoService;
import com.zcsy.manage.service.company.IOperationCompanyService;
import com.zcsy.manage.service.system.IDictService;
import com.zcsy.manage.service.system.IRoleService;
import com.zcsy.manage.service.system.IUserService;
import com.zcsy.manage.web.common.LogUtils;

/**
 * @Title: OperationCompanyController.java
 * @Package： com.zcsy.manage.web.base
 * @Description: 运营团队信息控制层管理类
 * @author liuying 1075817474@qq.com
 * @Copyright: 2015 武汉中财数元信息技术有限公司 All rights reserved.
 * @date 2016年4月6日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */
@Controller
@RequestMapping(value = "/operationcompany")
public class OperationCompanyController {

	@Autowired
	private IOperationCompanyService companyService;

	@Autowired
	private IDictService dictService;
	
	@Autowired
	private ICellInfoService cellInfoService;
	
	@Autowired
	private IRoleService roleService;

	@Autowired
	private IUserService userService;
	
	/**
	 * @Description 公司信息关键字检索<br>
	 * @param pNo
	 *            当前页码
	 * @param companyName
	 *            公司名称
	 * @param companyType
	 *            公司类型
	 * @param req
	 *            用户请求
	 * @return 跳转页面URL
	 * @author liuying 1075817474@qq.com
	 * @date 2016年4月7日
	 * @see
	 */
	@RequestMapping(value = "companyList", method = RequestMethod.GET)
	public String companyList(Model model, Integer pNo, Integer pSize, String companyName,
			HttpServletRequest req) {

		if (pNo == null) {
			pNo = Constants.PAGE_NO;
		}

		Integer pageSize;
		if (pSize == null) {
			pageSize = Constants.PAGE_SIZE;
		} else {
			switch (pSize) {
				case 0: pageSize = Constants.PAGE_SIZE;
				break;
				case 1: pageSize = Constants.PAGE_SIZE_TWENTY;
				break;
				case 2: pageSize = Constants.PAGE_SIZE_FIFTY;
				break;
				default:pageSize = Constants.PAGE_SIZE;
				break;
			}
		}
		
		// 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
		PageHelper.startPage(pNo, pageSize);

		Company company = new Company();

		if (StringUtils.isNotEmpty(companyName)) {
			company.setCompanyName(companyName);
		}

		List<Company> companys = companyService.selectByKeyword(company);
		PageInfo<Company> info = new PageInfo<Company>(companys);

		model.addAttribute("company", info);
		model.addAttribute("currentPage", pNo);
		model.addAttribute("pSize", pSize);
		model.addAttribute("companyName", companyName);

		List<Dict> pageSizes = dictService.getDictFromCache("pageSize");
		model.addAttribute("pageSizes", pageSizes);

		return "base/company/operationCompanyList";
	}

	/**
	 * @Description 公司信息编辑<br>
	 * @param id  主键id
	 * @return 编辑页面链接
	 * @author liuying 1075817474@qq.com
	 * @date 2016年4月7日
	 * @see
	 */
	@RequestMapping(value = "editcompany", method = RequestMethod.GET)
	public String editcompany(Model model, String id) {
		try {
			if (String.valueOf(Constants.STATE_DISABLED).equals(id)) {
				model.addAttribute("type", Constants.SAVE_TYPE);

			} else {
				Company company = companyService.selectByPrimaryKey(id);
				model.addAttribute("type", Constants.EDIT_TYPE);
				model.addAttribute("company", company);
			}

			List<Dict> companyTypes = dictService
					.getDictFromCache("companyType");
			model.addAttribute("companyTypes", companyTypes);

		} catch (Exception e) {
		}

		return "base/company/operationCompanyEdit";
	}

	/**
	 * @Description 编辑信息的保存<br>
	 * 
	 * @param companyName
	 *            公司名称
	 * @param companyType
	 *            公司类型
	 * @param companyAddr
	 *            公司地址
	 * @param phone
	 *            电话
	 * @param container
	 *            介绍
	 * @param sort
	 *            排序
	 * @param companyId
	 *            主键id
	 * @param request
	 *            用户请求
	 * @param response
	 *            响应
	 * @return 请求结果
	 * @author liuying 1075817474@qq.com
	 * @date 2016年4月7日
	 * @see
	 */
	@RequestMapping(value = "saveOrUpdateCompany", method = RequestMethod.POST)
	@ResponseBody
	public RequestJson saveOrUpdateCompany(String companyName,
			Short companyType, String companyAddr, String phone,
			String container, Integer sort, String companyId, String logo,
			HttpServletRequest request, HttpServletResponse response) {
		RequestJson result = new RequestJson();
		User user = (User)request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
		try {
			Company record = new Company();
			record.setCompanyName(companyName);
			record.setCompanyAddr(companyAddr);
			record.setPhone(phone);
			record.setIntroduces(container);
			record.setSort(sort);
			record.setLogo(logo);

			if (companyId != "" && !"0".equals(companyId)) {
				record.setId(companyId);
				record.setUpdateTime(new Date());
				companyService.update(record);
				LogUtils.insertLog("用户编辑运营团队信息", user.getId(), request);

			} else {
				record.setId(UniqueNumberUtils.get18UniqueNumber());
				record.setSendTime(new Date());
				companyService.insert(record);
				LogUtils.insertLog("用户新增运营团队信息", user.getId(), request);
			}
		} catch (Exception e) {
			result.setSuccess(false);
		}
		return result;
	}

	/**
	 * @Description 删除公司信息<br>
	 * @param companyIds
	 *            多个id
	 * @param req
	 *            用户请求
	 * @return 请求结果
	 * @author liuying 1075817474@qq.com
	 * @date 2016年4月7日
	 * @see
	 */
	@RequestMapping(value = "deleteCompany", method = RequestMethod.POST)
	@ResponseBody
	public RequestJson deleteCompany(@RequestParam("companyIds[]")String[] companyIds, HttpServletRequest request) {
		RequestJson result = new RequestJson();
		User user = (User)request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
		try {
			Integer cellCount = cellInfoService.selectCountByOIds(companyIds);
			Integer roleCount = roleService.selectCountByCompanyId(companyIds, Constants.USER_OPERATION);
			Integer userCount = userService.selectCountByCompanyId(companyIds, Constants.USER_OPERATION);
			if (cellCount > 0 || roleCount > 0 || userCount > 0) {
				result.setMsg("运营团队已被引用，不能删除！");
				result.setSuccess(false);
			} else {
				companyService.delete(companyIds);
				LogUtils.insertLog("用户删除运营团队信息", user.getId(), request);
				result.setSuccess(true);
			}
		} catch (NumberFormatException e) {
			result.setSuccess(false);
			result.setMsg("操作失败");
		}

		return result;
	}
	
	@RequestMapping(value="updateSort" , method = RequestMethod.GET)
	@ResponseBody
    public RequestJson updateSort( String id, HttpServletRequest request){
        RequestJson result = new RequestJson();
        User user = (User)request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        try {
        	Company company = companyService.selectByPrimaryKey(id);
        	if(company != null){
        		company.setUpdateTime(DateUtils.getDate());
        		companyService.updateSort(company);
        		LogUtils.insertLog("用户置顶运营团地信息", user.getId(), request);
        	}
        } catch (Exception e) {
            result.setMsg("操作失败");
            result.setSuccess(false);
        }
       
        return result;
    }
}
